/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mttestclient;

import java.io.*;
import java.net.*;
import java.util.concurrent.locks.*;
import java.util.logging.*;

/**
 *
 * @author 0914064 - Ross Aitken
 */
class ServerRequest extends Thread{

    private ClientModel client;
    private ReentrantLock clientLock;
    
    public ServerRequest(ClientModel client, ReentrantLock clientLock) {

        this.client = client;
        this.clientLock = clientLock;
    }
    
    public void castVote(String vote) // method for casting votes by the client
    {
        try{
            Socket socket = new Socket(client.getClientIP(), 
                    client.getClientPort()); 
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(socket.getInputStream()));
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

            out.println(vote);
            long time = System.nanoTime();
            while (!in.ready()) {
                //wait for awhile to get input
                if (Math.abs(System.nanoTime() - time) / 1000000 < 250)
                    yield(); // give up cpu time to other threads
                else
                    return; //just return if server doesn't reply
                
            }
            try {
                clientLock.lock();
                client.appendToServerFeedback(in.readLine());
            } finally {
                clientLock.unlock();
            }
        } catch (UnknownHostException ex) {
        } catch (IOException ex) {
        } 
    }

    @Override
    public void run() { // casts 2 votes, 1 after the other
            castVote(client.getClientVote());

            if (client.isVoteConfirmed()) {
                castVote(client.getClientSecondVote());
            }
    }
    
    
}
